/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package CreateTorrent;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.swing.JOptionPane;

/**
 *
 * @author THANG
 */
public class CreateTorrent {
    public static String[] split(File source,int lsize)  
    {  
        int noFile = 0;
        File[] fileFragments;
        String[] frgfName ;
        int theRest;
        int FRG_FSIZE = 1024*lsize;  
        String sourceFName = source.getName();  
        String realName = null;
        long sourceFSize = source.length();  


        noFile = (int) (sourceFSize / FRG_FSIZE);
        theRest = (int) (sourceFSize - (noFile * FRG_FSIZE));
        if(theRest == 0)
        {
            fileFragments = new File[noFile];  
            frgfName = new String[noFile];  
        }
        else
        {
            fileFragments = new File[noFile + 1];  
            frgfName = new String[noFile + 1];  
        }
        FileInputStream fis = null;
        try
        {      

            fis = new FileInputStream(source);  
                
            String Fileinfo = new String(sourceFName + "," + String.valueOf(sourceFSize));  
            System.out.println("Info: " + Fileinfo + "\n");  
            System.out.println("NoFile: " + noFile + "\n");  
            realName = sourceFName.substring(0, sourceFName.lastIndexOf("."));  
            int i = 0;
            while (i < noFile) 
            {   
                byte[] data = new byte[FRG_FSIZE];  
                int count = fis.read(data);
                
                frgfName[i] = getSHA_1(data);  
                fileFragments[i] = new File("temp\\" + frgfName[i]);  
                     
                FileOutputStream fos = new FileOutputStream(fileFragments[i]);  
  
                fos.write(data);  
                fos.close();  
                String frgFileInfo = new String(frgfName[i] + "," + String.valueOf(FRG_FSIZE));
                System.out.printf("info chunks " + (i + 1) + " :" + frgFileInfo + "\n");
                i++;
            }  
            if (theRest != 0) 
            {    
                byte[] data = new byte[theRest];  
                int count = fis.read(data); 
                
                frgfName[noFile] = getSHA_1(data);  
                fileFragments[noFile] = new File("temp\\" + frgfName[noFile]);
                
                FileOutputStream fos = new FileOutputStream(fileFragments[noFile]);  
                fos.write(data);  
                fos.close();               
                String frgFileInfo = new String(frgfName[noFile] + "," + String.valueOf(theRest)); 
                System.out.printf("info chunks " + (i + 1) + " :" + frgFileInfo + "\n");
            }  
  
        } 
        catch (Exception e) 
        {  
            System.out.println("Error in Splitting"+e);  
            JOptionPane.showMessageDialog(null, "Error in Splitting File \n"+e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);  
            return null;  
        }  
        finally
        {
            if(fis != null)
            {
                try {
                    fis.close();
                } catch (IOException ex) {
                    
                }
            }
            writeAToren(realName+".toren",frgfName,theRest,sourceFName.substring(sourceFName.lastIndexOf("."),sourceFName.length() ));
        }
        return frgfName;  
  } 
    
  public static String getSHA_1(byte[] data)
  {
      try 
      {       
        MessageDigest digest = MessageDigest.getInstance("SHA-1");      
        byte[] hash = digest.digest(data);
        String result = "";
        for ( byte b : hash ) 
        {
            result += Integer.toHexString(b + 256);
        }
        return result;
      } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException("No SHA-1 implementation? Really?");
    }
  }
  
  public static void writeAToren(String File,String[] frgfName,int theRest, String extend)
  {
		BufferedWriter bw = null;
                int n = frgfName.length;
		try
		{
			bw = new BufferedWriter(new FileWriter(File));
			String str = "";
                        bw.write(extend);
                        bw.newLine();
			bw.write(Integer.toString(n));
			bw.newLine();
			for(int i = 0; i< n ; i++)
			{
				str = frgfName[i];
				bw.write(str);
				bw.newLine();				
			}	
                        bw.write(Integer.toString(theRest));
		}
		catch(FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if(bw != null)
				{
					bw.flush();
					bw.close();
				}
			}
			catch(IOException e)
			{
				e.printStackTrace();
			}
		}      
  }
  
  
  public static void main(String ar[])  
  {    
    String[] str = CreateTorrent.split(new File("Jellyfish.jpg"),512);  
    //MergeFile mf=new MergeFile(); 
    //mf.mergeFiles(str,"pdf");
    
  }  
}
